package com.crud.web.controller;

import com.crud.domain.ResultVo;
import com.crud.entity.Dept;
import com.crud.entity.Emp;
import com.crud.service.DeptService;
import com.crud.service.EmpService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hyh
 * @date 2023/06/29 18:35:14
 */
@RestController
@RequestMapping("emp")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;

    @GetMapping("{pageNum}/{pageSize}")
    public ResultVo findAll(@PathVariable Integer pageNum, @PathVariable Integer pageSize, HttpSession session) {
        List<Emp> empList = empService.findAll(pageNum, pageSize);
        session.setAttribute("pageNum", pageNum);
        session.setAttribute("pageSize", pageSize);
        List<Dept> deptList = deptService.findAll();
        PageInfo<Emp> pageInfo = new PageInfo<>(empList);
        Map<String, Object> map = new HashMap<>();
        map.put("pageInfo", pageInfo);
        map.put("deptList", deptList);
        return ResultVo.success(map);
    }

    @PostMapping("other")
    public ResultVo findByOther(@RequestBody Map<String, String> map, HttpSession session) {
        Integer pageNum = session.getAttribute("pageNum")==null?1:(Integer) session.getAttribute("pageNum");
        Integer pageSize = session.getAttribute("pageSize")==null?5:(Integer) session.getAttribute("pageSize");
        map.put("pageSize", String.valueOf(pageSize));
        map.put("pageNum", String.valueOf(pageNum));
        System.out.println("================================");
        System.out.println(map);
        List<Emp> empList = empService.findByOther(map);
        PageInfo<Emp> pageInfo = new PageInfo<>(empList);
        return ResultVo.success(pageInfo);
    }

    @DeleteMapping("{id}")
    public ResultVo delete(@PathVariable Integer id) {
        int rows = empService.delete(id);
        return rows > 0 ? ResultVo.success("删除成功") : ResultVo.failure("删除失败");
    }

    @PutMapping()
    public ResultVo dept(@RequestBody Emp emp) {
        int rows = empService.update(emp);
        return rows > 0 ? ResultVo.success("修改成功") : ResultVo.failure("修改失败");
    }

    @PostMapping()
    public ResultVo save(@RequestBody Emp emp) {
        int rows = empService.save(emp);
        return rows > 0 ? ResultVo.success("添加成功", emp) : ResultVo.failure("添加失败");
    }
}
